package cn.tj.wenda.cloud.mapper;

import cn.tj.wenda.cloud.util.LoginUser;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.annotation.RegisterMapper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.List;

@RegisterMapper
public interface CloudSelectMapper<T> {

    @SelectProvider(type = SQLProvider.class, method = "dynamicSQL")
    long countByExample(Object example);

    @SelectProvider(type = SQLProvider.class, method = "dynamicSQL")
    T selectByPrimaryKey(Object key);

    @SelectProvider(type = SQLProvider.class, method = "dynamicSQL")
    List<T> selectByExample(Object example);

    class SQLProvider extends MapperTemplate {

        public SQLProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
            super(mapperClass, mapperHelper);
        }

        public String countByExample(MappedStatement ms) {
            Class<?> entityClass = getEntityClass(ms);
            StringBuilder sql = new StringBuilder("SELECT ");
            if (isCheckExampleEntityClass()) {
                sql.append(SqlHelper.exampleCheck(entityClass));
            }
            sql.append(SqlHelper.exampleCountColumn(entityClass));
            sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
            sql.append(CloudSqlHelper.exampleWhereClause());
            sql.append(SqlHelper.exampleForUpdate());
            return sql.toString();
        }

        public String selectByPrimaryKey(MappedStatement ms) {
            final Class<?> entityClass = getEntityClass(ms);
            //将返回值修改为实体类型
            setResultType(ms, entityClass);
            StringBuilder sql = new StringBuilder();
            sql.append(SqlHelper.selectAllColumns(entityClass));
            sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
            sql.append(CloudSqlHelper.wherePKColumns(entityClass));
            return sql.toString();
        }

        public String selectByExample(MappedStatement ms) {
            Class<?> entityClass = getEntityClass(ms);
            //将返回值修改为实体类型
            setResultType(ms, entityClass);
            StringBuilder sql = new StringBuilder("SELECT ");
            if (isCheckExampleEntityClass()) {
                sql.append(SqlHelper.exampleCheck(entityClass));
            }
            sql.append("<if test=\"distinct\">distinct</if>");
            //支持查询指定列
            sql.append(SqlHelper.exampleSelectColumns(entityClass));
            sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
            sql.append(CloudSqlHelper.exampleWhereClause());
            sql.append(SqlHelper.exampleOrderBy(entityClass));
            sql.append(SqlHelper.exampleForUpdate());
            return sql.toString();
        }
    }
}

